package com.open.annotation.aspect;

import cn.hutool.crypto.digest.MD5;
import com.open.annotation.Limit;
import com.open.annotation.RepeatSubmit;
import com.open.bean.vo.OpenVo;
import com.open.exception.WebException;
import com.open.util.OpenRequestUtil;
import com.open.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Base64;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {


    @Before(value = "@annotation(com.open.annotation.RepeatSubmit)")
    public void doBefore(JoinPoint joinPoint) throws WebException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null){
            HttpServletRequest request = attributes.getRequest();
            final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            final RepeatSubmit repeatSubmit = signature.getMethod().getAnnotation(RepeatSubmit.class);
            String url = request.getRequestURL().toString();
            log.info("url ==={}",url);
            String params = Arrays.toString(joinPoint.getArgs());
            log.info("params ==={}",params);
            MD5 md5 = MD5.create();
            String digestHex16 = md5.digestHex16(url+params);
            String state = RedisUtil.get(digestHex16);
            if (state == null){
                RedisUtil.set(digestHex16,"1001",repeatSubmit.time());
            }else {
                throw new WebException(repeatSubmit.msg());
            }
        }
    }


}
